package com.breaktian.assemble.http.retrofit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by tiankeke on 2017/5/24.
 * 此类属于基础类，使用时可以在这个上面再封一层
 * 此类不使用retrofit 直接使用okhttp发送请求
 * 单例模式
 */

public class OkHttpUtils {

    private static OkHttpUtils instance;
    private final OkHttpClient mOkHttpClient;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpUtils(){
        mOkHttpClient = new OkHttpClient();
    }

    public static OkHttpUtils get(){
        if(instance==null){
            synchronized (OkHttpUtils.class){
                if(instance==null){
                    instance = new OkHttpUtils();
                }
            }
        }

        return instance;
    }


    /**
     * post json
     * 异步
     * */
    public void postJson(String url, String json, Callback callback){
        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(JSON, json);
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        //发送请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 异步get请求
     * */
    public void get(String url, Callback callback){
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .build();
        //发送请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 异步post键值对
     * */
    public void post(String url, HashMap<String,String> params,Callback callback){
        //创建一个RequestBody builder
        FormBody.Builder formBody = new FormBody.Builder();

        Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String val = entry.getValue();
            formBody.add(key,val);
        }
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(formBody.build())
                .build();
        //发送请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }




}
